package com.imooc.business.core.executor.query.base;//package com.imooc.business.core.executor.query.base;
//
//import cn.mashang.report.modules.core.bussiness.constant.ReportBuiltInConstant;
//import cn.mashang.report.modules.core.infra.repository.entity.RuleMetadataEntity;
//import cn.mashang.report.modules.query.business.constant.BusinessConstant;
//import cn.mashang.report.modules.query.business.constant.QueryDesignDbConstant;
//import cn.mashang.report.modules.query.business.constant.SymbolConstant;
//import cn.mashang.report.modules.query.helper.ChartType;
//import cn.mashang.report.modules.query.infra.repository.designer.ReportResultRespository;
//import cn.mashang.report.modules.query.infra.repository.designer.demonstrate.ReportDemonstrateRepository;
//import cn.mashang.report.modules.query.infra.repository.designer.demonstrate.base.ReportBaseDemonstrateRepository;
//import cn.mashang.report.modules.query.infra.repository.designer.query.QueryExecRepository;
//import cn.mashang.report.modules.query.infra.repository.designer.request.TableExecRequest;
//import cn.mashang.report.modules.query.infra.repository.entity.TReportQueryAppChartIndex;
//import cn.mashang.report.modules.query.request.QueryExectRequest;
//import cn.mashang.report.modules.query.response.QueryDataResponse;
//import cn.mashang.vxiao.datadict.modules.report.enums.Dimension;
//import cn.mashang.vxiao.datadict.modules.report.enums.ReportPeriodType;
//import com.google.common.collect.Lists;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.collections.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//
//import java.util.*;
//import java.util.function.Function;
//import java.util.stream.Collectors;
//
///**
// * @Description: 图表
// * @Author guyuefeng
// * @Date: 2022-10-19 09:37
// */
//@Slf4j
//public abstract class ReportChartResultRespository<T,k> extends ReportBaseDemonstrateRepository<T,k>  implements ReportResultRespository<T,k>, ReportDemonstrateRepository<T> {
//
//    @Autowired
//    private QueryExecRepository queryExecRepository;
//
//    @Value("${report.noDataReturn}")
//    private Integer noDataReturn;
//
//    @Override
//    public void buildResult(TableExecRequest request){
//        log.info("query chart, appId:{}, groupId:{}, realType:{}, timeType:{}, graphFlag:{}, startDate:{},endDate:{}, this:{}",
//                request.getAppId(), request.getGroup().getGroupId(), request.getRealType(),request.getTimeType(),
//                request.getGraphFlag(), request.getStartDate(), request.getEndDate(), this.getClass().getSimpleName());
//        TableExecRequest.Chart chart = request.getChart();
//        List<TReportQueryAppChartIndex> tReportQueryAppChartIndices = chart.getTReportQueryAppChartIndices();
//        Map<Long, RuleMetadataEntity> signIdMap = chart.getSignIdMap();
//        Map<Long, String> styleMap = chart.getStyleMap();
//        String patten = chart.getPatten();
//        String pgPatten = chart.getPgPatten();
//        List<String> filterColumnNameList = request.getColumnNameList();
//        Integer filterChartType = chart.getChartType();
//        List<QueryDataResponse.TableChart> dataList = chart.getDataList();
//        List<QueryDataResponse.TableChartRank> rankList = chart.getRankList();
//
//        List<T> organList = getOrganList(request);
//        if (CollectionUtils.isEmpty(organList)){
//            return;
//        }
//        log.info("query chart, appId:{}, groupId:{}, realType:{}, timeType:{}, graphFlag:{}, startDate:{},endDate:{}, organList.size:{}",
//                request.getAppId(), request.getGroup().getGroupId(), request.getRealType(),request.getTimeType(),
//                request.getGraphFlag(), request.getStartDate(), request.getEndDate(), organList.size());
//        Map<Object, Map<String, Object>> dataMap = getDataMap(request, organList);
//        log.info("query chart, appId:{}, groupId:{}, realType:{}, timeType:{}, graphFlag:{}, startDate:{},endDate:{}, dataMap.size:{}",
//                request.getAppId(), request.getGroup().getGroupId(), request.getRealType(),request.getTimeType(),
//                request.getGraphFlag(), request.getStartDate(), request.getEndDate(), dataMap.size());
//        if (noDataReturn(dataMap)){
//            log.info("query chart, appId:{}, groupId:{}, noDataReturn, realType:{}, timeType:{}, graphFlag:{}, startDate:{},endDate:{}, dataMap.size:{}",
//                    request.getAppId(), request.getGroup().getGroupId(), request.getRealType(),request.getTimeType(),
//                    request.getGraphFlag(), request.getStartDate(), request.getEndDate(), dataMap.size());
//            return;
//        }
//
//        for (TReportQueryAppChartIndex tReportQueryAppChartIndex : tReportQueryAppChartIndices) {
//            Long chartIndexId = tReportQueryAppChartIndex.getId();
//            Integer chartType = tReportQueryAppChartIndex.getChartType();
//            Boolean supportRun = supportRun(ChartType.parse(chartType));
//            if (!supportRun){
//                continue;
//            }
//            //前端匹配对应的样式数据
//            if (Objects.nonNull(filterChartType) && !filterChartType.equals(chartType)){
//                continue;
//            }
//
//            // 每一种样式下面 t_report_query_app_chart_index 获取到对应的指标id的值
//            String indexIds = tReportQueryAppChartIndex.getIndexIds();
//            //前端匹配对应的字段展示
//            List<String> indexIdList = filterColumnIds(filterColumnNameList, indexIds, signIdMap);
//            if (CollectionUtils.isEmpty(indexIdList)){
//                continue;
//            }
//            int indexArrLength = indexIdList.size();
//            List<String> signList = new ArrayList<>(indexArrLength);
//            List<String> signNames = new ArrayList<>(indexArrLength);
//            indexIdList.stream().peek(indexId -> {
//                signList.add(signIdMap.get(Long.valueOf(indexId)).getSign());
//                signNames.add(signIdMap.get(Long.valueOf(indexId)).getName());
//            }).count();
//
//            if (ChartType.CHART.getType() == chartType){
//                log.info("query chart, appId:{}, groupId:{}, operateChart, chartIndexId:{}, indexArrLength:{} ,dataMap.size:{}, dateList.size:{}",
//                        request.getAppId(), request.getGroup().getGroupId(), chartIndexId, indexArrLength, dataMap.size(), organList.size());
//                operateChart(signNames, signList, styleMap, tReportQueryAppChartIndex, indexArrLength, organList,
//                         patten, pgPatten, dataMap, dataList);
//                log.info("query chart, appId:{}, groupId:{}, operateChart, chartIndexId:{}, indexArrLength:{} ,dataMap.size:{}, dateList.size:{}, dataList.size:{}",
//                        request.getAppId(), request.getGroup().getGroupId(), chartIndexId, indexArrLength, dataMap.size(), organList.size(), dataList.size());
//            } else if (ChartType.CHART_LIST.getType() == chartType){
//                log.info("query chart, appId:{}, groupId:{}, operateChartRank, chartIndexId:{}, indexArrLength:{}, organList.size:{}, dataMap.size:{}",
//                        request.getAppId(), request.getGroup().getGroupId(), chartIndexId, indexArrLength, organList.size(), dataMap.size());
//                operateChartRank(signNames, signList, dataMap, indexArrLength, organList, rankList);
//                log.info("query chart, appId:{}, groupId:{}, operateChartRank, chartIndexId:{},  indexArrLength:{}, organList.size:{}, dataMap.size:{}, rankList.size:{}",
//                        request.getAppId(), request.getGroup().getGroupId(), chartIndexId, indexArrLength, organList.size(), dataMap.size(), rankList.size());
//            }
//        }
//    }
//
//    /**
//     * 处理图表数据
//     * @author: guyuefeng
//     * @date: 2022/10/19 16:45
//     */
//    public void operateChart(List<String> signNames, List<String> signList, Map<Long, String> styleMap,
//                             TReportQueryAppChartIndex tReportQueryAppChartIndex, int indexArrLength, List<T> dateList,
//                             String patten, String pgPatten, Map<Object, Map<String, Object>> dataMap, List<QueryDataResponse.TableChart> dataList){
//        QueryDataResponse.TableChart tableChart = new QueryDataResponse.TableChart();
//        tableChart.setWidth(1);
//        tableChart.setHeight(1);
//        tableChart.setTitle(StringUtils.join(signNames, SymbolConstant.COMMA));
//        List<QueryDataResponse.TableChart.Item> itemList = new ArrayList<>();
//
//        for (int i=0; i<indexArrLength; i++) {
//            String sign = signList.get(i);
//            String signName = signNames.get(i);
//            QueryDataResponse.TableChart.Item item = new QueryDataResponse.TableChart.Item();
//            item.setType(styleMap.get(tReportQueryAppChartIndex.getId()));
//            item.setTitle(signName);
//
//            List<QueryDataResponse.TableChart.Item.DataDTO> dataDTOS = new ArrayList<>();
//            QueryDataResponse.TableChart.Item.DataDTO dataDTO = new QueryDataResponse.TableChart.Item.DataDTO();
//            dataDTO.setData(Lists.newArrayList());
//            dataDTOS.add(dataDTO);
//            for (T currentDate : dateList) {
//                String date = getFormatDate(currentDate, patten);
//                Map<String, Object> objMap = Optional.ofNullable(dataMap.get(getFormatDate(currentDate, pgPatten))).orElse(new HashMap<>());
//
//                QueryDataResponse.TableChart.Item.DataDTO innerDataDTO = new QueryDataResponse.TableChart.Item.DataDTO();
//                innerDataDTO.setName(date);
//                innerDataDTO.setValue(Objects.isNull(objMap.get(sign)) ? "0" : String.valueOf(objMap.get(sign)));
//
//                dataDTO.getData().add(innerDataDTO);
//            }
//
//            item.setDataList(dataDTOS);
//            itemList.add(item);
//        }
//        tableChart.setItemList(itemList);
//        dataList.add(tableChart);
//    }
//
//    /**
//     * 处理排行榜数据
//     * @author: guyuefeng
//     * @param: signNames
//     * @param: signList
//     * @param: dataMap
//     * @param: indexArrLength
//     * @param: organList
//     * @param: rankList
//     * @date: 2022/11/1 14:59
//     */
//    private void operateChartRank(List<String> signNames, List<String> signList, Map<Object, Map<String, Object>> dataMap,
//                                  int indexArrLength, List<T> organList, List<QueryDataResponse.TableChartRank> rankList){
//        if (dataMap.size() == 0){
//            return;
//        }
//        for (int i=0; i<indexArrLength; i++) {
//            String sign = signList.get(i);
//            String signName = signNames.get(i);
//
//            QueryDataResponse.TableChartRank tableChartRank = new QueryDataResponse.TableChartRank();
//            tableChartRank.setWidth(1);
//            tableChartRank.setHeight(1);
//            tableChartRank.setTitle(signName);
//
//            List<QueryDataResponse.TableChartRank.DataDTO> itemList = Lists.newLinkedList();
//
//            for (T organ : organList) {
//                QueryDataResponse.TableChartRank.DataDTO dataDTO = new QueryDataResponse.TableChartRank.DataDTO();
//
//                dataDTO.setName(getName(organ));
//                dataDTO.setPhoto(getOrganPhoto(organ));
//                k organId = getOrganId(organ);
//                dataDTO.setOrganId(String.valueOf(organId));
//
//                if (dataMap.containsKey(organId)) {
//                    Map<String, Object> indexMap = dataMap.get(organId);
//                    dataDTO.setCount(indexMap.get(sign).toString());
//                } else {
//                    //分页之后，每页匹配到的机构，不再提供默认值，直接不展示
//                    log.info("----->>>> query chart operateChartRank continue, organId:{}, dataMap:{}",organId, dataMap);
//                    continue;
//                }
//                itemList.add(dataDTO);
//            }
//
//            itemList = itemList.stream().sorted((o1, o2) -> Integer.valueOf(o2.getCount()) - Integer.valueOf(o1.getCount()))
//                    .collect(Collectors.toList());
//            for (int j=0,len=itemList.size(); j<len; j++){
//                QueryDataResponse.TableChartRank.DataDTO dataDTO = itemList.get(j);
//                dataDTO.setRank(j+1);
//            }
//            tableChartRank.setDatas(itemList);
//            rankList.add(tableChartRank);
//        }
//    }
//
//
//
//    /**
//     *
//     * @author: guyuefeng
//     * @param: request
//     * @param: ruleSign
//     * @param: indexSigns
//     * @param: pattern
//     * @date: 2022/10/19 19:41
//     */
//    protected Map<Object, Map<String,Object>> execChartQuery(QueryExectRequest request, String ruleSign, Set<String> indexSigns,
//                                                        String pattern, Integer pageSize, Integer offset){
////        request.setPageSize(pageSize);
////        request.setOffset(offset);
//        List<Map<String, Object>> mapList = queryExecRepository.execChartQuery(request, ruleSign, indexSigns, pattern);
//
//        if (CollectionUtils.isEmpty(mapList)){
//            return new HashMap<>();
//        }
//        return mapList.stream().collect(Collectors.toMap(m->m.get(QueryDesignDbConstant.DATE), v->v));
//    }
//
//    /**
//     * 执行数据查询
//     * @author: guyuefeng
//     * @param: request
//     * @param: startDate
//     * @param: endDate
//     * @param: timeType
//     * @param: ruleSign
//     * @param: indexSigns
//     * @param: pageSize
//     * @param: offset
//     * @date: 2022/10/31 11:52
//     */
//    protected Map<Object, Map<String,Object>> execQuery(QueryExectRequest request, Date startDate, Date endDate, Integer timeType,
//                                                        String ruleSign, Set<String> indexSigns, Integer pageSize, Integer offset){
//        QueryExectRequest.QueryExectRequestBuilder builder = QueryExectRequest.builder();
//        List<Long> userIds = request.getUserIds();
//        List<String> groupIds = request.getGroupIds();
//        List<Long> schoolIds = request.getSchoolIds();
//
//        boolean execFlag = false;
//        String userName = "";
//        if (CollectionUtils.isNotEmpty(userIds)) {
//            builder.userIds(userIds).dimension(Dimension.USER);
//            userName = ReportBuiltInConstant.USER_ID;
//            execFlag = true;
//        }
//        if (CollectionUtils.isNotEmpty(groupIds)) {
//            builder.groupIds(groupIds).dimension(Dimension.GROUP);
//            userName = ReportBuiltInConstant.GROUP_ID;
//            execFlag = true;
//        }
//        if (CollectionUtils.isNotEmpty(schoolIds)) {
//            builder.schoolIds(schoolIds).dimension(Dimension.SCHOOL);
//            userName = ReportBuiltInConstant.SCHOOL_ID;
//            execFlag = true;
//        }
//        if (!execFlag){
//            return new HashMap<>();
//        }
//        QueryExectRequest queryExectRequest = builder.startTime(startDate).endTime(endDate).
//                periodType(ReportPeriodType.parse(timeType)).pageSize(pageSize).offset(offset).build();
//        List<Map<String, Object>> mapList = queryExecRepository.execQuery(queryExectRequest, ruleSign, indexSigns);
//
//        if (CollectionUtils.isEmpty(mapList)){
//            return new HashMap<>();
//        }
//
//        String finalUserName = userName;
//        return mapList.stream().collect(Collectors.toMap(m->m.get(finalUserName), Function.identity(), (v1, v2)->{
//            for (Map.Entry<String, Object> entry : v1.entrySet()) {
//                String key = entry.getKey();
//                if (finalUserName.equals(key)){
//                    continue;
//                }
//                Object value1 = Objects.isNull(entry.getValue()) ? 0 : entry.getValue();
//                Object value2 = Objects.isNull(v2.get(key)) ? 0 : v2.get(key);
//                v2.put(key, Double.valueOf(value1.toString()) + Double.valueOf(value2.toString()));
//            }
//            return v2;
//        }));
//    }
//
//    /**
//     * 过滤想要的字段
//     * @author: guyuefeng
//     * @param: filterColumnIdList
//     * @param: indexIdList
//     * @param: signIdMap
//     * @date: 2022/11/17 10:44
//     */
//    private List<String> filterColumnIds(List<String> filterColumnNameList, String indexIds, Map<Long, RuleMetadataEntity> signIdMap){
//        if (StringUtils.isEmpty(indexIds)){
//            return null;
//        }
//        List<String> indexIdList = Arrays.asList(indexIds.split(SymbolConstant.COMMA));
//        if (CollectionUtils.isEmpty(filterColumnNameList)){
//            return indexIdList;
//        }
//
//        RuleMetadataEntity defaultEntity = new RuleMetadataEntity();
//        List<String> resIndexIdList = indexIdList.stream().
//                filter(indexId -> filterColumnNameList.contains(signIdMap.getOrDefault(Long.parseLong(indexId), defaultEntity).getSign())).
//                distinct().collect(Collectors.toList());
//        return resIndexIdList;
//    }
//
//    @Override
//    public Boolean noDataReturn(Map<Object, Map<String, Object>> map) {
//        return Objects.equals(noDataReturn, BusinessConstant.NO_DATA_RETURN_YES) &&
//                (Objects.isNull(map) || map.size() == 0);
//    }
//
//    /**
//     * 获取 组织|时间 数据
//     * @author: guyuefeng
//     * @param: request
//     * @date: 2022/10/19 16:44
//     */
//    protected List<T> getOrganList(TableExecRequest request){
//        return null;
//    }
//
//    protected String getName(T organ){
//        return null;
//    }
//
//    protected <K>K getOrganId(T organ){
//        return null;
//    }
//
//    protected String getOrganPhoto(T organ){
//        return null;
//    }
//
//    protected String getFormatDate(T date, String extraInfo){
//        return null;
//    }
//
//    /**
//     * 获取指标数据
//     * @author: guyuefeng
//     * @date: 2022/10/19 16:45
//     */
//    protected abstract Map<Object, Map<String, Object>> getDataMap(TableExecRequest request, List<T> dateList);
//
//    protected abstract Boolean supportRun(ChartType chartType);
//
//}
